package com.wenqiner.requesttool.util.file;

import com.wenqiner.requesttool.core.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rhf
 * @date 2023-03-24
 **/
public class CsvFileParser extends AbstractFileParser {
    public static final Logger log = LoggerFactory.getLogger(CsvFileParser.class);

    /**
     * 解析文件
     *
     * @param filePath 文件路径
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.String>>
     * @author rhf
     */
    @Override
    public List<Map<String, String>> parse(String filePath) {
        try (BufferedReader bufferedReader = super.inputStream(filePath)) {
            String s = bufferedReader.readLine();
            String[] keys = s.split(FIELD_SEPARATOR);
            int mapCapacity = keys.length * 4 / 3 + 1;
            String data;
            List<Map<String, String>> list = new ArrayList<>();
            while (null != (data = bufferedReader.readLine())) {
                String[] dataArray = data.split(FIELD_SEPARATOR);
                Map<String, String> rowMap = new HashMap<>(mapCapacity);
                for (int i = 0; i < keys.length; i++) {
                    rowMap.put(keys[i], dataArray[i]);
                }
                list.add(rowMap);
            }
            return list;
        } catch (IOException e) {
            log.error("读取文件异常, error msg:{}, \ne:{}", e.getMessage(), e);
            throw new CustomException("读取文件异常");

        }
    }

    /**
     * 写入到文件
     *
     * @param filePath  文件路径
     * @param data      数据
     * @param fieldName 字段名
     * @author rhf
     */
    @Override
    public void writerToFile(String filePath, List<Map<String, String>> data, List<String> fieldName) {
        try (PrintWriter writer = super.getWriter(filePath)) {
            writer.println(String.join(FIELD_SEPARATOR, fieldName));
            data.forEach(d ->
                    writer.println(
                            String.join(FIELD_SEPARATOR, d.values()))
            );
        } catch (IOException e) {
            log.error("写入文件异常, error msg:{}, \ne:{}", e.getMessage(), e);
            throw new CustomException("写入文件异常");
        }
    }
}
